package libs

import (
	"github.com/gomodule/redigo/redis"
	"time"
)

var (
	RedisClient *redis.Pool
)

func RedisInit(addr string, db int) {
	// 建立连接池
	RedisClient = &redis.Pool{
		// maxidle 最大空闲数
		// maxactive 最大活动连接数
		MaxIdle:     8,
		MaxActive:   1024,
		IdleTimeout: 180 * time.Second,
		Dial: func() (redis.Conn, error) {
			cli, err := redis.Dial("tcp", addr)
			if err != nil {
				return nil, err
			}
			// 选择db
			_, err = cli.Do("SELECT", db)
			if err != nil {
				return nil, err
			}
			return cli, nil
		},
	}

}

func RedisGetStr(key string) (data string, err error) {
	var cli = RedisClient.Get()
	defer cli.Close()
	is_exist, err := redis.Bool(cli.Do("EXISTS", key))
	if err != nil {
		return "", err
	}
	if is_exist == false {
		return "nil", nil
	}
	str, err := redis.Bytes(cli.Do("get", key))
	if err != nil {
		return "", err
	}
	return string(str), nil
}

func RedisSetStr(key string, value string) (err error) {
	var cli = RedisClient.Get()
	defer cli.Close()
	_, err = cli.Do("set", key, value)
	return err
}

func RedisSetSet(key string, value string) (err error) {
	var cli = RedisClient.Get()
	defer cli.Close()
	_, err = cli.Do("SADD", key, value)
	return err
}

//fmt.Println(RedisGetSet("20181129"))
func RedisGetSet(key string) (value []string, err error) {
	var cli = RedisClient.Get()
	defer cli.Close()
	result, err := redis.Strings(cli.Do("SMEMBERS", key))
	return result, err
}
